package cn.edu.zjitc.servlet.code.ex05;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/responseDemo")
public class ResponseDemoServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 设置响应内容类型和编码
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write("<h2>Response 示例</h2>");

        // 2. 设置状态码
        resp.setStatus(HttpServletResponse.SC_OK);
        // 3. 示例：重定向到百度
         resp.sendRedirect("https://www.baidu.com");
        // 4. 示例：文件下载
        // String fileName = URLEncoder.encode("test.txt", "UTF-8");
        // resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        // resp.getWriter().write("下载内容");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

